/**
 * AppController.js
 * 
 * 前端核心控制器 - 协调 UI 模块与通信层
 * 
 * 职责：
 * 1. 初始化所有视图模块（MessageView、InputView、ToolListView、ToolResultView）
 * 2. 协调 UI 模块与 VSCodeAdapter 的交互
 * 3. 处理业务逻辑（消息发送、工具执行、工具确认等）
 * 4. 绑定全局事件和后端消息监听
 */

(function() {
    'use strict';

    class AppController {
        constructor() {
            this.vscode = new window.VSCodeAdapter(); // 用于向后端发送消息，订阅后端的消息

            // 负责消息展示区域的逻辑。动态渲染消息内容（如用户消息、系统消息）。支持消息的滚动、更新等功能。
            this.messageView = new window.MessageView({
                onFileOpen: (filePath) => this.vscode.post('openFile', { path: filePath })
            });

            this.inputView = new window.InputView({
                onSend: (text, files) => this.handleSend(text, files)
            });

            this.toolResultView = new window.ToolResultView();

            this.methodSelectorView = new window.MethodSelectorView({
                onRequestMethods: () => this.requestMethodList()
            });

            // 保存当前执行的工具名称，用于关联结果
            this.pendingToolName = null;
            this.assistMode = 'auto';
            this._initAssistModeControls();

            this._bindGlobalEvents();
            this._registerListeners();

            // 初始化完项目，请求一些历史数据
            this.vscode.post('webviewReady');
        }

        async handleSend(text, files) {
            await window.ErrorBoundary.wrapAsync(async () => {
                const methodIds = this.methodSelectorView.getSelectedMethodIds();
                if (!methodIds.length) {
                    this.messageView.addMessage('assistant', '请先在下拉框中选择至少一个方法。');
                    return;
                }
                this.inputView.setBusy(true);
                this.vscode.post('startGeneration', { methodIds, assistMode: this.assistMode });
            }, 'Failed to start generation');
        }

        /**
         * 处理手动工具执行
         * @param {string} id - 工具ID
         * @param {string} name - 工具名称
         * @param {object} args - 工具参数
         */
        async handleToolExec(id, name, args) {
            await window.ErrorBoundary.wrapAsync(async () => {
                // 保存工具名称，用于后续关联结果
                this.pendingToolName = name || id;
                // 手动调用工具：直接发送到后端，不在消息面板显示
                this.vscode.post('callTool', { toolId: id, toolName: name, args });
            }, `Failed to execute tool: ${name || id}`);
        }

        handleConfirmationResponse(messageId, approved) {
            // 1. 更新 UI
            this.messageView.updateConfirmationStatus(messageId, approved);
            // 2. 发送给后端
            this.vscode.post('toolConfirmationResponse', { messageId, approved });
        }

        _bindGlobalEvents() {
            const selectProjectBtn = document.getElementById('select-project-button');
            const ckgButton = document.getElementById('generate-ckg-button');
            const configButton = document.getElementById('open-config-button');
            const assistButton = document.getElementById('assist-mode-button');

            if (selectProjectBtn) selectProjectBtn.onclick = () => {
                this.vscode.post('selectProject');
            };
            if (ckgButton) ckgButton.onclick = () => {
                this.vscode.post('generateCKG');
            };
            if (configButton) configButton.onclick = () => {
                this.vscode.post('openUserConfig');
            };
            if (assistButton) {
                assistButton.onclick = (event) => {
                    event.stopPropagation();
                    this.toggleAssistDropdown();
                };
            }
            document.addEventListener('click', () => this.hideAssistDropdown());
        }

        _initAssistModeControls() {
            this.assistModeButton = document.getElementById('assist-mode-button');
            this.assistModeDropdown = document.getElementById('assist-mode-dropdown');
            if (this.assistModeDropdown) {
                this.assistModeDropdown.querySelectorAll('.assist-option').forEach(option => {
                    option.addEventListener('click', (event) => {
                        const mode = option.dataset.mode || 'auto';
                        event.stopPropagation();
                        this.setAssistMode(mode);
                    });
                });
            }
            this.setAssistMode('auto');
        }

        toggleAssistDropdown() {
            if (!this.assistModeDropdown) {
                return;
            }
            this.assistModeDropdown.classList.toggle('show');
        }

        hideAssistDropdown() {
            if (this.assistModeDropdown) {
                this.assistModeDropdown.classList.remove('show');
            }
        }

        setAssistMode(mode) {
            this.assistMode = mode === 'human' ? 'human' : 'auto';
            if (this.assistModeDropdown) {
                this.assistModeDropdown.querySelectorAll('.assist-option').forEach(option => {
                    option.classList.toggle('selected', option.dataset.mode === this.assistMode);
                });
            }
            this.hideAssistDropdown();
        }

        _registerListeners() {
            const v = this.vscode;

            v.on('response', msg => { // 订阅response类型的消息
                const loading = document.querySelector('.msg.loading');
                if(loading) loading.remove();
                this.messageView.addMessage('assistant', msg.text);
            });

            v.on('streamChunk', msg => { // 订阅流式消息
                const loading = document.querySelector('.msg.loading');
                if(loading) loading.remove();
                this.messageView.appendToMessage(msg.messageId, msg.chunk);
            });

            v.on('methodList', msg => this.methodSelectorView.setMethods(msg.methods));
            v.on('projectSelected', msg => {
                if (msg.path) {
                    this.messageView.addMessage('assistant', `被测项目路径：${msg.path}`);
                }
                this.methodSelectorView.clearSelection();
                this.requestMethodList();
            });
            v.on('generationStatus', msg => this.handleGenerationStatus(msg.status));
            v.on('generationComplete', msg => this.handleGenerationComplete(msg.success));

            v.on('toolResult', msg => {
                // 🟢 只有手动调用的工具结果才显示在工具结果面板
                // AI调用的工具(source='ai')不显示在工具面板,仅在消息流中显示
                if (msg.result.source === 'manual') {
                    // 确保结果包含时间戳和工具名称
                    const result = {
                        ...msg.result,
                        timestamp: msg.result.timestamp || Date.now(),
                        toolName: this.pendingToolName || msg.toolName || 'Unknown Tool'
                    };
                    this.toolResultView.addResult(result);
                }
                // 清除保存的工具名称
                this.pendingToolName = null;
            });

            v.on('filesSelected', msg => {
                msg.files.forEach(f => this.inputView.addAttachment(f));
            });
            
            // 🟢 修复: 完整处理工具确认请求
            v.on('toolConfirmation', msg => {
                 this.messageView.addToolConfirmationMessage(
                     msg.toolCall, 
                     msg.messageId, 
                     (approved) => this.handleConfirmationResponse(msg.messageId, approved)
                 );
            });

            v.on('clearSuccess', () => this.messageView.clear());
            
            // 恢复聊天历史记录
            v.on('restoreHistory', msg => {
                this.messageView.restoreHistory(msg.messages);
            });

            // 恢复手动工具执行历史
            v.on('restoreManualHistory', msg => {
                this.toolResultView.restoreManualHistory(msg.history);
            });
        }

        requestMethodList() {
            this.vscode.post('requestMethodList');
        }

        handleGenerationStatus(status) {
            if (!status) {
                return;
            }
            const prefix = status.level === 'error'
                ? '❌'
                : status.level === 'success'
                    ? '✅'
                    : 'ℹ️';
            const text = `${prefix} ${status.message}`;
            if (status.files && status.files.length > 0) {
                this.messageView.addFileSummary(text, status.files, (filePath) => {
                    this.vscode.post('openFile', { path: filePath });
                });
            } else {
                this.messageView.addMessage('assistant', text);
            }
        }

        handleGenerationComplete(success) {
            this.inputView.setBusy(false);
            if (success) {
                this.methodSelectorView.clearSelection();
            }
        }

        /**
         * 清理资源
         */
        dispose() {
            if (this.vscode) {
                this.vscode.dispose();
            }
            console.log('[AppController] Disposed');
        }
    }

    window.AppController = AppController;
})();
